package main

import (
	"flag"
	"fmt"
	"os"
	"path/filepath"

	"github.com/schollz/progressbar/v3"
)

func main() {
	// var path string
	// var muti bool
	// 读取命令行参数
	path := flag.String("path", "", "rename forder path (necessary, example '.').")
	prefix := flag.String("pre", "", "the prefix rename.")
	muti := flag.Bool("muti", false, "lunch muti extends.")
	flag.Parse()

	if *path == "" {
		fmt.Fprintf(os.Stderr, "param -path is necessary, example '.'.")
		return
	}

	fmt.Println(*path, *muti)
	// 读取目标文件下的所有文件，如果存在目录则报告异常并退出
	entrys, err := os.ReadDir(*path)
	if err != nil {
		fmt.Fprintf(os.Stderr, "os.ReadDir err: %v\n", err)
	}

	for _, entry := range entrys {
		if entry.IsDir() {
			fmt.Fprintf(os.Stderr, "find sub forder '%s' in forder %s", entry.Name(), *path)
			return
		}
	}

	// 获取执行文件路径
	exe_path, _ := os.Executable()

	num := 0

	files := make([][]string, 0)
	old_paths := make(map[string]bool)
	new_paths := make(map[string]bool)

	if *muti {
		// 直接修改，跳过exe
		for _, entry := range entrys {
			if entry.Name() == filepath.Base(exe_path) {
				continue
			}
			old_path := filepath.Join(*path, entry.Name())
			new_path := filepath.Join(*path, fmt.Sprintf("%s%d%s", *prefix, num, filepath.Ext(entry.Name())))

			files = append(files, []string{old_path, new_path})
			old_paths[old_path] = true
			new_paths[new_path] = true
			num += 1
		}

		for key := range old_paths {
			if new_paths[key] {
				fmt.Fprintf(os.Stderr, "rename fail ! file %s always exits.", filepath.Base(key))
				return
			}
		}

		bar := progressbar.Default(int64(len(files)))

		for _, item := range files {
			if err := os.Rename(item[0], item[1]); err != nil {
				fmt.Fprintf(os.Stderr, "rename err: %v\n", err)
				os.Exit(1)
			}
			bar.Add(1)
		}

		return
	}

	// 否则扫描文件后缀数量，默认情况下，超过一种则退出(排除自生可能是.exe或者无后缀)
	extends := make(map[string]bool)
	for _, entry := range entrys {
		if filepath.Base(exe_path) == entry.Name() {
			continue
		}
		ext := filepath.Ext(entry.Name())
		extends[ext] = true
	}

	if len(extends) > 1 {
		fmt.Fprintf(os.Stderr, "extends exceed 1, if you hope more extends add -muti.")
		return
	}

	// 直接修改，跳过exe
	for _, entry := range entrys {
		if entry.Name() == filepath.Base(exe_path) {
			continue
		}
		old_path := filepath.Join(*path, entry.Name())
		new_path := filepath.Join(*path, fmt.Sprintf("%s%d%s", *prefix, num, filepath.Ext(entry.Name())))

		files = append(files, []string{old_path, new_path})
		old_paths[old_path] = true
		new_paths[new_path] = true
		num += 1
	}

	for key := range old_paths {
		if new_paths[key] {
			fmt.Fprintf(os.Stderr, "rename fail ! file %s always exits.", filepath.Base(key))
			return
		}
	}

	bar := progressbar.Default(int64(len(files)))
	for _, item := range files {
		if err := os.Rename(item[0], item[1]); err != nil {
			panic("os.Rename error. " + err.Error())
		}
		bar.Add(1)
	}

	fmt.Println("Rename successed !")

}
